package com.zklh.leetcode.top100.problem141;

import com.zklh.leetcode.tree.model.ListNode;

/**
 * @author Nelson
 * @Description 快慢指针实现
 * @create 2023-02-07 16:15
 */
public class Solution2 {
    public boolean hasCycle(ListNode head) {
        if (head == null) {
            return false;
        }

        ListNode slowPoint = head;
        ListNode quicklyPoint = head.next;
        while (quicklyPoint != slowPoint) {
            if (quicklyPoint == null || quicklyPoint.next == null) {
                return false;
            }
            quicklyPoint = quicklyPoint.next.next;
            slowPoint = slowPoint.next;
        }

        return true;
    }

    public static void main(String[] args) {
        Solution2 solution = new Solution2();

        ListNode head = new ListNode(3);
        head.next = new ListNode(2);
        head.next.next = new ListNode(0);
        head.next.next.next = new ListNode(-4);
        head.next.next.next.next = head.next;

        System.out.println(solution.hasCycle(head));
    }
}
